package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Poi;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.navi.AmapNaviPage;
import com.amap.api.navi.AmapNaviParams;
import com.amap.api.navi.AmapNaviTheme;
import com.amap.api.navi.AmapNaviType;
import com.amap.api.navi.AmapPageType;
import com.amap.api.navi.enums.PathPlanningStrategy;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.services.route.WalkStep;
import com.amap.api.track.AMapTrackClient;
import com.amap.api.track.ErrorCode;
import com.amap.api.track.OnTrackLifecycleListener;
import com.amap.api.track.TrackParam;
import com.amap.api.track.query.entity.CorrectMode;
import com.amap.api.track.query.entity.DenoiseMode;
import com.amap.api.track.query.entity.DriveMode;
import com.amap.api.track.query.entity.MapMatchMode;
import com.amap.api.track.query.entity.Point;
import com.amap.api.track.query.entity.RecoupMode;
import com.amap.api.track.query.entity.ThresholdMode;
import com.amap.api.track.query.entity.Track;
import com.amap.api.track.query.model.AddTrackRequest;
import com.amap.api.track.query.model.AddTrackResponse;
import com.amap.api.track.query.model.DistanceRequest;
import com.amap.api.track.query.model.DistanceResponse;
import com.amap.api.track.query.model.QueryTerminalRequest;
import com.amap.api.track.query.model.QueryTerminalResponse;
import com.amap.api.track.query.model.QueryTrackRequest;
import com.amap.api.track.query.model.QueryTrackResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.SPUtil;
import com.xiaocz.common.utils.TimeUtil;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.activities.activity.dialog.DialogBadgeActivity;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.interfaces.CancelUtils;
import com.xiaocz.hblsubstitutedriving.interfaces.RoundRefresh;
import com.xiaocz.hblsubstitutedriving.model.OrderInfo;
import com.xiaocz.hblsubstitutedriving.model.OrderPrice;
import com.xiaocz.hblsubstitutedriving.model.Reason;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.utils.INaviInfoCallbackListener;
import com.xiaocz.hblsubstitutedriving.utils.SimpleOnTrackLifecycleListener;
import com.xiaocz.hblsubstitutedriving.utils.SimpleOnTrackListener;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Time:2019/7/4
 * Created by xiaocz
 * Describe 订单过程中
 */
public class OrderCourseActivity extends BaseActivity implements RoundRefresh, LocationSource, AMapLocationListener {

    private static final String CHANNEL_ID_SERVICE_RUNNING = "CHANNEL_ID_SERVICE_RUNNING";

    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.btn_right)
    TextView btnRight;
    @BindView(R.id.tv_distance_and_amount)
    TextView tvDistanceAndAmount;
    @BindView(R.id.activity_track_service_map)
    TextureMapView mapView;
    @BindView(R.id.btn_dh)
    TextView btnDh;
    @BindView(R.id.btn_phone)
    TextView btnPhone;
    @BindView(R.id.btn_wait)
    TextView btnWait;
    @BindView(R.id.tv_wait_time)
    TextView tvWaitTime;
    @BindView(R.id.btn_order_state)
    TextView btnOrderState;

    /**
     * DATA
     */
    private AMapTrackClient aMapTrackClient;
    private long terminalId;
    private OrderInfo orderInfo;
    private String orderNo;
    private OrderPrice orderPrice;//计费方式-单价
    private Timer timer, timeWait;
    private boolean isWait;
    private long minutes = 0;//, cnt = 0;//等待时间-分钟/总时间

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_order_course;
    }

    @Override
    protected void initData() {
        super.initData();
        webGetPrice(orderNo);
    }

    private AMap aMap;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mapView.getMap().moveCamera(CameraUpdateFactory.zoomTo(14));
        mapView.onCreate(savedInstanceState);
        aMapTrackClient = new AMapTrackClient(getApplicationContext());// 不要使用Activity作为Context传入
        aMapTrackClient.setInterval(2, 10);
        terminalId = Long.parseLong(String.valueOf(SPUtil.get("TERMINAL_ID", 0L)));
        CancelUtils.setCancelRefresh(this);
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        UiSettings uiSettings = aMap.getUiSettings();
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        uiSettings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        uiSettings.setZoomControlsEnabled(false);//设置缩放按钮是否可见
        MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.showMyLocation(true);
        myLocationStyle.strokeColor(Color.argb(30, 30, 30, 30));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.showBuildings(false);
    }


    /**
     * 提前结束订单
     */
    private void dialogEndOrder() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
        builder.setMessage("结束后将直接进入收费页面，请确认是否结束？");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                webEndOrder(null, 0, Constants.location.getAddress(), Constants.location.getLongitude(), Constants.location.getLatitude());
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @OnClick({R.id.btn_right, R.id.btn_dh, R.id.btn_order_state, R.id.btn_phone, R.id.btn_badge, R.id.btn_urgency, R.id.btn_wait})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_right://取消订单
                if ("取消订单".equals(btnRight.getText().toString())) {
                    webOrderCancelList();
                } else {
                    dialogEndOrder();
                }
                break;
            case R.id.btn_order_state:
                dialogNext();
                break;
            case R.id.btn_dh://导航
                AmapNaviParams params;
                if (orderInfo != null && !TextUtils.isEmpty(orderInfo.getMudilat()) && !TextUtils.isEmpty(orderInfo.getMudilong())) {
                    Poi end = new Poi(orderInfo.getMudiaddress(), new LatLng(Double.parseDouble(orderInfo.getMudilat()), Double.parseDouble(orderInfo.getMudilong())), "");
                    params = new AmapNaviParams(end);
                } else {
                    params = new AmapNaviParams(null, null, null, AmapNaviType.DRIVER);
                }
                params.setUseInnerVoice(true);
                params.setShowExitNaviDialog(false);
                params.setTheme(AmapNaviTheme.WHITE);
                params.setRouteStrategy(PathPlanningStrategy.DRIVING_SHORTEST_DISTANCE);//距离最短
                AmapNaviPage.getInstance().showRouteActivity(getApplicationContext(), params, new INaviInfoCallbackListener() {
                    @Override
                    public View getCustomNaviBottomView() {
                        return customNBottomView();
                    }

                    @Override
                    public View getCustomNaviView() {
                        return customNCreateView();
                    }
                }, CustomAmapRouteActivity.class);
                break;
            case R.id.btn_badge://电子工牌
                DialogBadgeActivity.show(mContext);
                break;
            case R.id.btn_phone://拨打电话
                callPhone(orderInfo.getCusphone());
                break;
            case R.id.btn_urgency://紧急情况
                App.getInstance().showMessage("紧急情况");
                break;
            case R.id.btn_wait://中途等待
                if (!btnWait.getText().toString().contains(getResources().getString(R.string.text_wait_cf))) {
                    if (isWait) {
                        btnWait.setText(getResources().getString(R.string.text_wait));
                        timeWait.cancel();
                        tvWaitTime.setVisibility(View.GONE);
                    } else {
                        btnWait.setText(getResources().getString(R.string.text_off_wait));
                        tvWaitTime.setVisibility(View.VISIBLE);
                        setWaitTime();
                    }
                    isWait = !isWait;
                }
                break;
        }
    }

    private void invoking() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                query();
            }
        }, 10000, 2500);//每隔一秒使用handler发送一下消息,也就是每隔一秒执行一次,一直重复执行
    }


    /**
     * 等时费
     */
    private String getStringTime(long cnt) {
        long hour = cnt / 3600;
        long min = cnt % 3600 / 60;
        long second = cnt % 60;
        minutes = cnt / 60;
        if(orderPrice!=null){
            long cCTime=min-orderPrice.getFreewaittime();
            if (cCTime>=0 && btnRight!=null) {
                btnRight.setText("结束订单");
                return String.format(Locale.CHINESE, "产生等候费%d元\n已等待%02d:%02d:%02d", cCTime+1,hour, min, second);
            }else {
                return String.format(Locale.CHINESE, "已等待%02d:%02d:%02d", hour, min, second);
            }
        }else {
            return String.format(Locale.CHINESE, "已等待%02d:%02d:%02d", hour, min, second);
        }
    }

    private void setWaitTime() {
        timeWait = new Timer();
        timeWait.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        String waitTime=getStringTime(timeNumber++);
                        if (tvWaitTime != null) {
                            tvWaitTime.setText(waitTime);
                        }
                    }
                });
            }
        }, 0, 1000);
    }

    /**
     * 距离查询
     */
    private void query() {
        final DistanceRequest distanceRequest = new DistanceRequest(
                Constants.SERVICE_ID,
                terminalId,
                System.currentTimeMillis() - 24 * 60 * 60 * 1000, //开始时间
                System.currentTimeMillis(),// 结束时间
                orderInfo.getTraceId(),// 轨迹id
                CorrectMode.DRIVING,//是否纠偏
                RecoupMode.DRIVING,//是否进行距离补偿
                50
        );
        aMapTrackClient.queryDistance(distanceRequest, new SimpleOnTrackListener() {
            @Override
            public void onDistanceCallback(DistanceResponse distanceResponse) {
                if (distanceResponse.isSuccess()) {
                    count(distanceResponse.getDistance() / 1000.00);
                }
            }
        });
    }

    /**
     * 订单结束获取轨迹点
     */
    private void getTrack() {
        loadingDialogShow(false);
        QueryTrackRequest queryTrackRequest = new QueryTrackRequest(
                Constants.SERVICE_ID,
                terminalId,
                orderInfo.getTraceId(),// 轨迹id，传-1表示查询所有轨迹
                System.currentTimeMillis() - 24 * 60 * 60 * 1000, //开始时间
                System.currentTimeMillis(),// 结束时间
                DenoiseMode.DENOSE,// 去噪
                MapMatchMode.MAPMATCH,// 绑路
                ThresholdMode.GPS_WIFI_THRESHOLD,// 不进行精度过滤
                DriveMode.DRIVING,// 当前仅支持驾车模式
                RecoupMode.DRIVING,// 距离补偿
                50,// 距离补偿，只有超过5km的点才启用距离补偿
                1,  // 结果应该包含轨迹点信息
                pageSize,  // 返回第1页数据，由于未指定轨迹，分页将失效
                999 // 每页条数
        );
        aMapTrackClient.queryTerminalTrack(queryTrackRequest, new SimpleOnTrackListener() {

            @Override
            public void onQueryTrackCallback(QueryTrackResponse queryTrackResponse) {
                if (queryTrackResponse.isSuccess()) {// 查询成功，tracks包含所有轨迹及相关轨迹点信息
                    List<Track> tracks = queryTrackResponse.getTracks();
                    try {
                        List<Point> pointList = tracks.get(0).getPoints();
                        for (Point p : pointList) {
                            LatLng latLngs = new LatLng(p.getLat(), p.getLng());
                            list.add(latLngs);
                        }
                        if (pointList.size() == 999) {
                            pageSize++;
                            getTrack();
                        } else {
                            if (Constants.location != null && Constants.location.getLongitude() > 0 && Constants.location.getLatitude() > 0) {
                                webEndOrder(list, tracks.get(0).getDistance() / 1000.00, Constants.location.getAddress(), Constants.location.getLongitude(), Constants.location.getLatitude());
                            } else {
                                App.getInstance().showMessage(getResources().getString(R.string.none_location));
                            }
                        }
                    } catch (Exception e) {
                        if (Constants.location != null && Constants.location.getLongitude() > 0 && Constants.location.getLatitude() > 0) {
                            webEndOrder(list, tracks.get(0).getDistance() / 1000.00, Constants.location.getAddress(), Constants.location.getLongitude(), Constants.location.getLatitude());
                        } else {
                            App.getInstance().showMessage(getResources().getString(R.string.none_location));
                        }
                        e.printStackTrace();

                    }
                } else {
                    onDismiss();
                    App.getInstance().showMessage("轨迹查询失败");// 查询失败
                }
            }
        });
    }

    private List<LatLng> list = new ArrayList<>();
    private int pageSize = 1;

    /**
     * 费用计算
     */
    private void count(double distance) {
        if (orderPrice != null) {
            BigDecimal decimal = new BigDecimal(String.valueOf(distance));
            try {
                if (distance > orderPrice.getQibukm().doubleValue()) {// 超出起步公里计费
                    BigDecimal b1 = decimal.subtract(orderPrice.getQibukm());// 得到超出公里
                    b1 = b1.divide(orderPrice.getChaokm());// 得到超出倍数
                    b1 = b1.setScale(0, BigDecimal.ROUND_UP);
                    b1 = b1.multiply(orderPrice.getChaochuprice());// 得到超出价格
                    if (tvDistanceAndAmount != null) {
                        tvDistanceAndAmount.setText(String.valueOf("已行驶:" + distance + "km,起步价:" + orderPrice.getQibuprice() + "元，超出价格:" + b1.setScale(2, BigDecimal.ROUND_UP).toString() + "元"));
                    }
                    if (tvNCDistance != null) {
                        tvNCDistance.setText(String.valueOf("已行驶:" + distance + "km,起步价:" + orderPrice.getQibuprice() + "元，超出价格:" + b1.setScale(2, BigDecimal.ROUND_UP).toString() + "元"));
                    }
                    if (tvNDistance != null) {
                        tvNDistance.setText(String.valueOf("已行驶:" + distance + "km,起步价:" + orderPrice.getQibuprice() + "元，超出价格:" + b1.setScale(2, BigDecimal.ROUND_UP).toString() + "元"));
                    }
                } else {
                    if (tvDistanceAndAmount != null) {
                        tvDistanceAndAmount.setText(String.valueOf("已行驶:" + distance + "km,起步价:" + orderPrice.getQibuprice() + "元，起步里程:" + orderPrice.getQibukm() + "km"));
                    }
                    if (tvNCDistance != null) {
                        tvNCDistance.setText(String.valueOf("已行驶:" + distance + "km,起步价:" + orderPrice.getQibuprice() + "元"));
                    }
                    if (tvNDistance != null) {
                        tvNDistance.setText(String.valueOf("已行驶:" + distance + "km,起步价:" + orderPrice.getQibuprice() + "元"));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean fixedPrice = false;

    /**
     * 获取计费单价
     */
    private void webGetPrice(final String orderNo) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/getOrderPriceRule", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<OrderPrice>>() {
                }.getType();
                response.setBody(response.getBody().replace("\"list\":[{", "").replace("}]", ""));
                RspModel<OrderPrice> rspModel = getAnalysis(response, type, " 获取计费单价");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null) {
                            orderPrice = rspModel.getData();
                            webOrderDetail(orderNo);
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }


    /**
     * 获取订单详情
     *
     * @param orderNo 订单编号
     */
    private void webOrderDetail(final String orderNo) {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/getOrderDetail", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<OrderInfo>>() {
                }.getType();
                RspModel<OrderInfo> rspModel = getAnalysis(response, type, " 获取订单详情");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null) {
                            orderInfo = rspModel.getData();
                            if (orderInfo.getCusphone() != null) {
                                btnPhone.setVisibility(View.VISIBLE);
                            }
                            if (orderInfo.getPricetype() == 1) {
                                fixedPrice = true;
                                tvDistanceAndAmount.setText(String.format(getString(R.string.text_ykj), orderInfo.getMoney()));
                                tvDistanceAndAmount.setVisibility(View.VISIBLE);
                            }
                            Constants.isRelink = true;
                            if (orderInfo.getOrderstatus() >= 4) {
                                App.getInstance().showMessage("订单已结束！");
                                finish();
                            }

                            SimpleDateFormat dateFormat = new SimpleDateFormat(Common.DateType.dateIF, Locale.CHINA);
                            try {
                                if (orderInfo.getStarttime() != null && !"".equals(orderInfo.getStarttime())) {//已经代驾出发
                                    timeNumber = (dateFormat.parse(orderInfo.getStarttime()).getTime() / 1000L) - (dateFormat.parse(orderInfo.getDaodatime()).getTime() / 1000L);
                                } else {//未出发
                                    timeNumber = TimeUtil.getLongStamp() - (dateFormat.parse(orderInfo.getDaodatime()).getTime() / 1000L);
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            Constants.driverWorkState = "2";//修改司机状态
                            if ("1".equals(orderInfo.getDrivestatus())) {//1-前往客户处
                                setTextState(1);
                            } else if ("2".equals(orderInfo.getDrivestatus())) {//2-到达客户处
                                startTrack(false);
                                setTextState(2);
                            } else if ("3".equals(orderInfo.getDrivestatus())) {//3-代驾中
                                startTrack(true);
                                setTextState(3);
                            } else if ("4".equals(orderInfo.getDrivestatus())) {//4-代驾结束
                                if (orderInfo.getOrderstatus() == 3) {//3已完成
                                    OrderGatheringActivity.show(mContext, orderInfo.getOrderNo());
                                }
                                finish();
                            } else {//5-未接单
                                finish();
                            }
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                            finish();
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    private long timeNumber;

    RouteSearch routeSearch;

    /**
     * 修改状态-标题
     *
     * @param state 2、3
     */
    private void setTextState(int state) {
        switch (state) {
            case 1://到达客户
                mTitle.setText("前往客户处");
                btnRight.setVisibility(View.VISIBLE);
                btnRight.setText("取消订单");
                btnOrderState.setEnabled(true);
                btnOrderState.setText("到达客户处");
                onWalkRoute();
                break;
            case 2:
                clearWalkRoute();
                mTitle.setText("准备出发");
                btnRight.setVisibility(View.VISIBLE);
                btnRight.setText("取消订单");
                btnOrderState.setEnabled(false);
                btnOrderState.setText("代驾出发");
                btnWait.setText(getResources().getString(R.string.text_wait_cf));
                btnWait.setVisibility(View.VISIBLE);
                tvWaitTime.setVisibility(View.VISIBLE);
                setWaitTime();
                final MediaPlayer mediaPlayer = App.getInstance().audioFocus(R.raw.ddkf_lmjd, false);
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (btnOrderState != null) {
                            btnOrderState.setEnabled(true);
                        }
                        if (App.getInstance().audioFocusManager != null) {
                            App.getInstance().audioFocusManager.releaseTheAudioFocus();
                            if (mediaPlayer.isPlaying()) {
                                mediaPlayer.stop();
                            }
                            mediaPlayer.release();
                        }
                    }
                });
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (btnOrderState != null) {
                            btnOrderState.setEnabled(true);
                        }
                    }
                }, mediaPlayer.getDuration());
                break;
            case 3:
                mTitle.setText("代驾中");
                btnRight.setVisibility(View.GONE);
                btnOrderState.setEnabled(false);
                btnOrderState.setText("代驾结束");
                if (!fixedPrice) {
                    btnWait.setVisibility(View.VISIBLE);
                    btnWait.setText(getResources().getString(R.string.text_wait));
                } else {
                    btnWait.setVisibility(View.GONE);
                }
                tvWaitTime.setVisibility(View.GONE);
                final MediaPlayer player = App.getInstance().audioFocus(R.raw.djdjcf, false);
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        if (btnOrderState != null) {
                            btnOrderState.setEnabled(true);
                        }
                        if (App.getInstance().audioFocusManager != null) {
                            App.getInstance().audioFocusManager.releaseTheAudioFocus();
                            if (player.isPlaying()) {
                                player.stop();
                            }
                            player.release();
                        }
                        onRoute();
                    }
                });
                btnDh.setVisibility(View.VISIBLE);
                if (!fixedPrice) {
                    btnWait.setVisibility(View.VISIBLE);
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (btnOrderState != null) {
                            btnOrderState.setEnabled(true);
                        }
                    }
                }, player.getDuration());
                break;
        }
    }

    /**
     * 直接进入导航
     */
    private void onRoute() {
        if (orderInfo != null && !TextUtils.isEmpty(orderInfo.getMudilat()) && !TextUtils.isEmpty(orderInfo.getMudilong())) {
            Poi end = new Poi(orderInfo.getMudiaddress(), new LatLng(Double.parseDouble(orderInfo.getMudilat()), Double.parseDouble(orderInfo.getMudilong())), "");
            AmapNaviParams params = new AmapNaviParams(null, null, end, AmapNaviType.DRIVER, AmapPageType.NAVI);
            params.setUseInnerVoice(true);
            params.setMultipleRouteNaviMode(false);
            params.setShowExitNaviDialog(false);
            params.setTheme(AmapNaviTheme.WHITE);
            params.setRouteStrategy(PathPlanningStrategy.DRIVING_SHORTEST_DISTANCE);//距离最短isDrawBackUpOverlay()
            AmapNaviPage.getInstance().showRouteActivity(getApplicationContext(), params, new INaviInfoCallbackListener() {
                @Override
                public View getCustomNaviBottomView() {
                    return customNBottomView();
                }

                @Override
                public View getCustomNaviView() {
                    return customNCreateView();
                }
            }, CustomAmapRouteActivity.class);
        }
    }

    /**
     * 步行导航
     */
    private void onWalkRoute() {
        if (orderInfo != null && !TextUtils.isEmpty(orderInfo.getChufalat()) && !TextUtils.isEmpty(orderInfo.getChufalong()) && Constants.getLocation() != null) {
            routeSearch = new RouteSearch(mContext);
            LatLonPoint latLonPointStart = new LatLonPoint(Constants.getLocation().getLatitude(),Constants.getLocation().getLongitude());
            LatLonPoint latLonPointEnd = new LatLonPoint(Double.parseDouble(orderInfo.getChufalat()), Double.parseDouble(orderInfo.getChufalong()));
            RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(latLonPointStart, latLonPointEnd);
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo);
            routeSearch.calculateWalkRouteAsyn(query);//开始算路
            routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
                @Override
                public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
                }

                @Override
                public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                }

                @Override
                public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {
                    if (i == 1000) {
                        drawWalkRoute(walkRouteResult.getPaths().get(0).getSteps());
                    } else {
                        App.getInstance().showMessage("步行路线规划失败！");
                    }
                }

                @Override
                public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
                }
            });
        } else {
            App.getInstance().showMessage(getResources().getString(R.string.none_location));
        }
    }

    /**
     * 订单流程更改
     */
    private void webUpdateOrderState(final int driveStatus, String address, double lng, double lat) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        asyncHttpPostFormData.addFormData("drivestatus", driveStatus);
        asyncHttpPostFormData.addFormData("chufaaddress", address);
        asyncHttpPostFormData.addFormData("chufalong", lng);
        asyncHttpPostFormData.addFormData("chufalat", lat);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/updateOrderDriverWorkStaus", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 订单流程更改");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            if (driveStatus == 3) {//到达客户处
                                aMapTrackClient.setTrackId(orderInfo.getTraceId()); // 启动轨迹服务
                                aMapTrackClient.startGather(onTrackListener);
                                setTextState(3);
                            } else {
                                setTextState(driveStatus);
                            }
                            if (driveStatus == 2) {
                                startTrack(false);
                            }
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }


    /**
     * 结束订单
     */
    private void webEndOrder(List<LatLng> latLng, double driveTotalMile, String address, double lng, double lat) {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        asyncHttpPostFormData.addFormData("mudiaddress", address);
        asyncHttpPostFormData.addFormData("mudilong", lng);
        asyncHttpPostFormData.addFormData("mudilat", lat);
        asyncHttpPostFormData.addFormData("drivetotalmile", driveTotalMile);
        asyncHttpPostFormData.addFormData("waitminute", minutes+1);//等待时间;
        asyncHttpPostFormData.addFormData("locusdata", new Gson().toJson(latLng));
        okHttpClient.post(Common.Constant.API_IP + "api/Order/finishOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, " 结束订单");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            Constants.driverWorkState = "1";//修改司机状态为空闲状态
                            OrderGatheringActivity.show(mContext, orderNo);
                            finish();
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 取消原因
     */
    private void webOrderCancelList() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("chosetype_id", "4");//type (1客户取消原因，2额外费用，3投诉原因，4司机取消原因)
        okHttpClient.post(Common.Constant.API_IP + "api/Order/ChoseContentList", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<List<Reason>>>() {
                }.getType();
                RspModel<List<Reason>> rspModel = getAnalysis(response, type, "取消原因");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            dialogOrderCancel(rspModel.getData());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 步骤执行提示
     */
    private void dialogNext() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        if ("到达客户处".equals(btnOrderState.getText().toString())) {
            float distance = 0;
            if (orderInfo != null && orderInfo.getChufalat() != null && orderInfo.getChufalong() != null && Constants.getLocation()!=null) {
                distance = AMapUtils.calculateLineDistance(new LatLng(Double.parseDouble(orderInfo.getChufalat()), Double.parseDouble(orderInfo.getChufalong())), new LatLng(Constants.getLocation().getLatitude(), Constants.getLocation().getLongitude()));
            }
            if (distance > 100) {
                builder.setMessage("您离客户还有一段距离呢！建议您到客户后再确认到达客户位置");
            } else {
                builder.setMessage("是否真实到达或接到客户？");
            }
        } else if ("代驾出发".equals(btnOrderState.getText().toString())) {
            builder.setMessage("将进入代驾导航页面，确定开始吗？");
        } else if ("代驾结束".equals(btnOrderState.getText().toString())) {
            builder.setMessage("代驾结束？");
        }
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Constants.getLocation() != null) {
                    if ("到达客户处".equals(btnOrderState.getText().toString())) {
                        webUpdateOrderState(2, Constants.location.getAddress(), Constants.location.getLongitude(), Constants.location.getLatitude());
                    } else if ("代驾出发".equals(btnOrderState.getText().toString())) {
                        if (timeWait != null) {//关闭等客时间
                            timeWait.cancel();
                            timeWait = null;
                        }
                        webUpdateOrderState(3, Constants.location.getAddress(), Constants.location.getLongitude(), Constants.location.getLatitude());
                    } else if ("代驾结束".equals(btnOrderState.getText().toString())) {
                        pageSize = 1;//重置分页
                        aMapTrackClient.stopGather(onTrackListener);
                    }
                } else {
                    App.getInstance().showMessage(getResources().getString(R.string.none_location));
                }

            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 显示-取消理由
     */
    private void dialogOrderCancel(List<Reason> reasonList) {
        final String[] cancelReason = new String[reasonList.size()];
        for (int i = 0; i < reasonList.size(); i++) {
            cancelReason[i] = reasonList.get(i).getContent();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择订单取消理由");
        builder.setItems(cancelReason, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                webOrderCancel(cancelReason[which]);
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 取消订单理由-提交
     */
    private void webOrderCancel(String cancelTxt) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        asyncHttpPostFormData.addFormData("canceltxt", cancelTxt);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/cancelOrder", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "取消订单");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus()) {
                            Constants.driverWorkState = "1";//修改司机状态为空闲状态
                            App.getInstance().showMessage("取消订单成功！");
                            finish();
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 布局轨迹
     */
    private void drawWalkRoute(List<WalkStep> walkStepList) {
        List<LatLonPoint> latLonPoints = new ArrayList<>();
        for (int i = 0; i < walkStepList.size(); i++) {
            latLonPoints.addAll(walkStepList.get(i).getPolyline());
        }

        LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
        PolylineOptions polylineOptions = new PolylineOptions();
        polylineOptions.color(Color.BLUE).width(26);
        if (latLonPoints.size() > 0) {// 起点
            LatLng latLng = new LatLng(latLonPoints.get(0).getLatitude(), latLonPoints.get(0).getLongitude());
            MarkerOptions markerOptions = new MarkerOptions().position(latLng)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            markerOptions.setFlat(false);
            walkRoute.add(aMap.addMarker(markerOptions));
        }
        if (latLonPoints.size() > 1) {// 终点
            LatLonPoint p = latLonPoints.get(latLonPoints.size() - 1);
            LatLng latLng = new LatLng(p.getLatitude(), p.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions().position(latLng)
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(),
                                    R.drawable.icon_client)));
            markerOptions.setFlat(false);
            walkRoute.add(aMap.addMarker(markerOptions));
        }
        for (LatLonPoint p : latLonPoints) {
            LatLng latLngs = new LatLng(p.getLatitude(), p.getLongitude());
            polylineOptions.add(latLngs);
            boundsBuilder.include(latLngs);
        }
        polyline = aMap.addPolyline(polylineOptions);
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 80));
    }

    private Polyline polyline;
    private List<Marker> walkRoute = new LinkedList<>();

    /**
     * 清除步行导航
     */
    private void clearWalkRoute() {
        for (Marker marker : walkRoute) {
            marker.remove();
        }
        walkRoute.clear();
        if (polyline != null) {
            polyline.remove();
        }
        polyline = null;
    }

    /**
     * 开启轨迹服务（用Terminal ID开启轨迹服务）
     * isTrack  是否开启轨迹
     */
    private void startTrack(final boolean isTrack) {
        aMapTrackClient.queryTerminal(new QueryTerminalRequest(Constants.SERVICE_ID, Constants.TERMINAL_NAME), new SimpleOnTrackListener() {
            @Override
            public void onQueryTerminalCallback(QueryTerminalResponse queryTerminalResponse) {
                if (queryTerminalResponse.isSuccess()) {
                    aMapTrackClient.addTrack(new AddTrackRequest(Constants.SERVICE_ID, terminalId), new SimpleOnTrackListener() {
                        @Override
                        public void onAddTrackCallback(AddTrackResponse addTrackResponse) {
                            if (addTrackResponse.isSuccess()) {
                                TrackParam trackParam = new TrackParam(Constants.SERVICE_ID, terminalId);
                                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    trackParam.setNotification(createNotification());
                                }
                                if (isTrack) {
                                    aMapTrackClient.startTrack(trackParam, new SimpleOnTrackLifecycleListener() {
                                        @Override
                                        public void onStartTrackCallback(int status, String msg) {
                                            if (status == ErrorCode.TrackListen.START_TRACK_SUCEE || status == ErrorCode.TrackListen.START_TRACK_SUCEE_NO_NETWORK || status == ErrorCode.TrackListen.START_TRACK_ALREADY_STARTED) {
                                                aMapTrackClient.setTrackId(orderInfo.getTraceId()); // 启动轨迹服务
                                                aMapTrackClient.startGather(onTrackListener);
                                            } else {
                                                Log.w(TAG, "error onStartTrackCallback, status: " + status + ", msg: " + msg);
                                                App.getInstance().showMessage("网络连接异常-轨迹！");
                                            }
                                        }
                                    });
                                } else {
                                    aMapTrackClient.startTrack(trackParam, onTrackListener);
                                }
                            } else {
                                App.getInstance().showMessage("网络请求失败，" + addTrackResponse.getErrorMsg());
                            }
                        }
                    });
                } else {
                    App.getInstance().showMessage("网络请求失败，" + queryTerminalResponse.getErrorMsg());
                }
            }
        });
    }

    /**
     * 轨迹采集监听
     */
    private OnTrackLifecycleListener onTrackListener = new SimpleOnTrackLifecycleListener() {
        @Override
        public void onStartGatherCallback(int status, String msg) {
            if (status == ErrorCode.TrackListen.START_GATHER_SUCEE || status == ErrorCode.TrackListen.START_GATHER_ALREADY_STARTED) {
                tvDistanceAndAmount.setVisibility(View.VISIBLE);
                if (!fixedPrice) {
                    invoking();
                }
            } else {
                App.getInstance().showMessage("轨迹采集异常，请注意网络连接！");
            }
        }

        @Override
        public void onStopGatherCallback(int status, String msg) {
            if (status != ErrorCode.TrackListen.STOP_GATHER_SUCCE) {
                App.getInstance().showMessage("停止" + status + msg);
            }
            getTrack();
            super.onStopGatherCallback(status, msg);
        }
    };

    /**
     * 导航中部提示
     */
    private View customNCreateView() {
        // 创建一个布局加载器的对象
        View view = LayoutInflater.from(mContext).inflate(R.layout.order_course_create, null);
        tvNDistance = view.findViewById(R.id.tv_distance);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.height = 100;
        view.setLayoutParams(params);
        return view;
    }

    private TextView tvNCDistance, tvNDistance;

    private View customNBottomView() {
        LinearLayout linearLayout = new LinearLayout(this);
        try {
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            tvNCDistance = new TextView(this);
            tvNCDistance.setGravity(Gravity.CENTER);
            tvNCDistance.setHeight(90);
            tvNCDistance.setMinWidth(300);
            linearLayout.setGravity(Gravity.CENTER);
            linearLayout.addView(tvNCDistance, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.height = 100;
            linearLayout.setLayoutParams(params);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return linearLayout;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    public static void show(Context context, String orderNo) {
        Intent intent = new Intent(context, OrderCourseActivity.class);
        //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("ORDER_NO", orderNo);
        context.startActivity(intent);
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            orderNo = bundle.getString("ORDER_NO");
        }
        return !TextUtils.isEmpty(orderNo);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (null != locationClient) {
            locationClient.onDestroy();
        }
        if (aMapTrackClient != null) {
            aMapTrackClient.stopTrack(new TrackParam(Constants.SERVICE_ID, terminalId), null);//停止轨迹服务
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timeWait != null) {
            timeWait.cancel();
            timeWait = null;
        }
    }


    /**
     * 在8.0以上手机，如果app切到后台，系统会限制定位相关接口调用频率
     * 可以在启动轨迹上报服务时提供一个通知，这样Service启动时会使用该通知成为前台Service，可以避免此限制
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private Notification createNotification() {
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID_SERVICE_RUNNING, "app service", NotificationManager.IMPORTANCE_LOW);
            nm.createNotificationChannel(channel);
            builder = new Notification.Builder(getApplicationContext(), CHANNEL_ID_SERVICE_RUNNING);
        } else {
            builder = new Notification.Builder(getApplicationContext());
        }
        Intent nfIntent = new Intent(OrderCourseActivity.this, OrderCourseActivity.class);
        nfIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        builder.setContentIntent(PendingIntent.getActivity(OrderCourseActivity.this, 0, nfIntent, 0))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("自己人代驾持续定位中")
                .setContentText("自己人代驾持续定位中");
        Notification notification = builder.build();
        return notification;
    }

    @Override
    public void onRoundRefresh(int type, String message) {
        if (type == 30) {
            App.getInstance().showMessage("用户已取消了该订单！");
            finish();
        }
    }

    private OnLocationChangedListener mListener;
    private AMapLocationClient locationClient;

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (locationClient == null) {
            //初始化定位
            locationClient = new AMapLocationClient(mContext);
            //初始化定位参数
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(7 * 1000);
            mLocationOption.setMockEnable(true);
            //设置定位参数
            locationClient.setLocationOption(mLocationOption);
            locationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                if (amapLocation.getLongitude() > 0 && amapLocation.getLatitude() > 0) {
                    Constants.location = amapLocation;
                }
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }
}
